#include <stdio.h>
#include <stdlib.h>
#include "vmath/vectormath_aos.h"

#define IMAGE_SIZE 800

const VmathVector3 g_cam_pos = { 2.0f, 2.0f, 2.0f };
const VmathVector3 g_zero = { 0.0f, 0.0f, 0.0f };
const VmathVector3 g_one = { 1.0f, 1.0f, 1.0f };

void ComputeColor(float x, float y, VmathVector3 *color) {
  vmathV3MakeFromElems(color, 1.0f, 0.0f, 0.0f);
}

int main(int argc, char **argv) {
  unsigned char *image;
  int x, y;
  FILE *fp;

  image = malloc(IMAGE_SIZE * IMAGE_SIZE * 4);
  if (!image) {
    fprintf(stderr, "Failed to allocate memory for the image.\n");
    exit(1);
  }

  for (y = 0; y < IMAGE_SIZE; ++y) {
    for (x = 0; x < IMAGE_SIZE; ++x) {
      int index = y * IMAGE_SIZE + x;
      float nx = (float) x / IMAGE_SIZE;
      float ny = (float) y / IMAGE_SIZE;
      VmathVector3 color;

      ComputeColor(nx, ny, &color);

      vmathV3MinPerElem(&color, &color, &g_one);
      vmathV3MaxPerElem(&color, &color, &g_zero);

      unsigned char r = (unsigned char)(255.0f * color.x);
      unsigned char g = (unsigned char)(255.0f * color.y);
      unsigned char b = (unsigned char)(255.0f * color.z);

      image[index*4 + 0] = b;
      image[index*4 + 1] = g;
      image[index*4 + 2] = r;
      image[index*4 + 3] = 255;
    }
  }

  fp = fopen("qjulia.tga", "wb");
  if (fp) {
    unsigned char tga_header[18] = {
      0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      IMAGE_SIZE & 0x00ff, (IMAGE_SIZE & 0xff00) >> 8,
      IMAGE_SIZE & 0x00ff, (IMAGE_SIZE & 0xff00) >> 8,
      32, 0
    };
    fwrite(tga_header, sizeof(tga_header), 1, fp);
    fwrite(image, IMAGE_SIZE * IMAGE_SIZE * 4, 1, fp);
    fclose(fp);
  }

  free(image);
  return 0;
}
